<?php
namespace Addons\TimedTask\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\TimedTask\Helper;
use Addons\TimedTask\Config\apiInfo;

/**
 * 客户阶段管理
 */
class TimedTask extends \BaseController
{
	public function index(){
		$info = apiInfo::$info;
		$arr =  json_decode(file_get_contents(DOXCX_FRAME_PATH . '/Addons/TimedTask/Data/TimedTask/index.txt'),1);
		$arr_api = [];
		$time = time();
		$h = Helper::getInstance();
		foreach ($info as $key => $val) {
			if(array_key_exists($key, $arr)){
				if($time > $arr[$key] + ($val*60)){
					$arr[$key] = $time;
					$arr_api[] = $h->get_http_server_name().'/Addons/TimedTask/Api/'.$key;
				}
			}else{
				$arr[$key] = $time;
				$arr_api[] = $h->get_http_server_name().'/Addons/TimedTask/Api/'.$key;
			}
		}
		$arr_json = json_encode($arr);
		file_put_contents(DOXCX_FRAME_PATH . '/Addons/TimedTask/Data/TimedTask/index.txt', $arr_json);
		if(count($arr_api) > 0){
			$this->exApi($arr_api);
		}
	}

	private function exApi($api){
		$mh = curl_multi_init();
		for ($i=0;$i<count($api);$i++) {
		     $conn[$i]=curl_init($api[$i]);
		      curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
		      curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
		      curl_setopt($conn[$i],CURLOPT_FOLLOWLOCATION,1);  //防止重定向
		      // curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
		      curl_multi_add_handle ($mh,$conn[$i]);
		}
		$active = null;
		do { $n=curl_multi_exec($mh,$active); }
		while ($active > 0);

		$result = true;
		for ($i=0;$i<count($api);$i++) {
		      $res[$i]=json_decode(curl_multi_getcontent($conn[$i]),1);	
		      // echo microtime()."<br>";
			// $res = curl_multi_getcontent($conn[$i]);
		      curl_close($conn[$i]);
		      if($res[$i]['code'] == 'error'){
				$result = false;
		      }
		}
		if($result == false){
			echo 'fail';
		}
		echo 'success';
	}

}